#region COPYRIGHT
//--------------------------------------------------------------------------------
// <copyright file="Curve.cs" company="starLiGHT Entertainment Studios">
//    Copyright (c) 2007, 2008, 2009, 2010, 2011
//       Roland Rosenkranz (Glatzemann@email.de)
//
//    Based on libnoise by Jason Bevins
//      Copyright (C) 2003, 2004 Jason Bevins (licensed under LGPL)
// </copyright>
// <license>
//   This file is part of starLiGHT.Noise.
//
//   starLiGHT.Noise is free software: you can redistribute it and/or modify
//   it under the terms of the GNU Lesser General Public License as published by
//   the Free Software Foundation, either version 3 of the License, or
//   (at your option) any later version.
//
//   starLiGHT.Noise is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU Lesser General Public License for more details.
//
//   You should have received a copy of the GNU Lesser General Public License
//   along with starLiGHT.Noise. If not, see http://www.gnu.org/licenses/.
//    
//   ADDITIONAL (commercial) LICENSES for starLiGHT.Noise are available on request.
// </license>
// <version>
// **************[ starLiGHT.Engine SVN ]**********************
// * $Rev:: 10385                 $:  Revision of last commit *
// * $Author:: unknown            $:  Author of last commit   *
// * $Date:: 2011-06-14 07:59:17 #$:  Date of last commit     *
// ************************************************************
// </version>
//--------------------------------------------------------------------------------
#endregion

namespace starLiGHT.Noise.Noise
{
    #region Using Statements
    using System;
    using System.Collections.Generic;
    using System.Text;

    #endregion

    /// This structure defines a control point.
    ///
    /// Control points are used for defining splines.
    public struct ControlPoint
    {

      /// The input value.
      public double inputValue;

      /// The output value that is mapped from the input value.
      public double outputValue;
    }

    /// Noise module that maps the output value from a source module onto an
    /// arbitrary function curve.
    ///
    /// @image html modulecurve.png
    ///
    /// This noise module maps the output value from the source module onto an
    /// application-defined curve.  This curve is defined by a number of
    /// <i>control points</i>; each control point has an <i>input value</i>
    /// that maps to an <i>output value</i>.  Refer to the following
    /// illustration:
    ///
    /// @image html curve.png
    ///
    /// To add the control points to this curve, call the AddControlPoint()
    /// method.
    ///
    /// Since this curve is a cubic spline, an application must add a minimum
    /// of four control points to the curve.  If this is not done, the
    /// GetValue() method fails.  Each control point can have any input and
    /// output value, although no two control points can have the same input
    /// value.  There is no limit to the number of control points that can be
    /// added to the curve.  
    ///
    /// This noise module requires one source module.
    public class Curve : Module
    {
        /// Number of control points on the curve.
        protected int controlPointCount;

        /// Array that stores the control points.
        protected List<ControlPoint> controlPoints;

        /// Constructor.
        public Curve() : base(1)
        {
            this.controlPoints = new List<ControlPoint>();
            this.controlPointCount = 0;
        }

        /// Destructor.
        ~Curve()
        {
        }

        /// Adds a control point to the curve.
        ///
        /// @param inputValue The input value stored in the control point.
        /// @param outputValue The output value stored in the control point.
        ///
        /// @pre No two control points have the same input value.
        ///
        /// @throw noise::ExceptionInvalidParam An invalid parameter was
        /// specified; see the preconditions for more information.
        ///
        /// It does not matter which order these points are added.
        public void AddControlPoint(double inputValue, double outputValue)
        {
            int insertionPos = this.FindInsertionPos(inputValue);
            this.InsertAtPos(insertionPos, inputValue, outputValue);
        }

        /// Deletes all the control points on the curve.
        ///
        /// @post All points on the curve are deleted.
        public void ClearAllControlPoints()
        {
            this.controlPoints.Clear();
            this.controlPointCount = 0;
        }

        /// Returns a pointer to the array of control points on the curve.
        ///
        /// @returns A pointer to the array of control points.
        ///
        /// Before calling this method, call GetControlPointCount() to
        /// determine the number of control points in this array.
        ///
        /// It is recommended that an application does not store this pointer
        /// for later use since the pointer to the array may change if the
        /// application calls another method of this object.
        public List<ControlPoint> GetControlPointArray()
        {
          return this.controlPoints;
        }

        /// Returns the number of control points on the curve.
        ///
        /// @returns The number of control points on the curve.
        public int GetControlPointCount()
        {
          return this.controlPointCount;
        }

        public override double GetValue(double x, double y, double z, double lowerXBound, double upperXBound, double lowerZBound, double upperZBound)
        {
            System.Diagnostics.Debug.Assert(sourceModule[0] != null, String.Empty);
            System.Diagnostics.Debug.Assert(this.controlPointCount >= 4, String.Empty);

            // Get the output value from the source module.
            double sourceModuleValue = sourceModule[0].GetValue(x, y, z, lowerXBound, upperXBound, lowerZBound, upperZBound);

            // Find the first element in the control point array that has an input value
            // larger than the output value from the source module.
            int indexPos;
            for (indexPos = 0; indexPos < this.controlPointCount; indexPos++)
            {
                if (sourceModuleValue < this.controlPoints[indexPos].inputValue)
                {
                    break;
                }
            }

            // Find the four nearest control points so that we can perform cubic
            // interpolation.
            int index0 = this.ClampValue(indexPos - 2, 0, this.controlPointCount - 1);
            int index1 = this.ClampValue(indexPos - 1, 0, this.controlPointCount - 1);
            int index2 = this.ClampValue(indexPos, 0, this.controlPointCount - 1);
            int index3 = this.ClampValue(indexPos + 1, 0, this.controlPointCount - 1);

            // If some control points are missing (which occurs if the value from the
            // source module is greater than the largest input value or less than the
            // smallest input value of the control point array), get the corresponding
            // output value of the nearest control point and exit now.
            if (index1 == index2)
            {
                return this.controlPoints[index1].outputValue;
            }

            // Compute the alpha value used for cubic interpolation.
            double input0 = this.controlPoints[index1].inputValue;
            double input1 = this.controlPoints[index2].inputValue;
            double alpha = (sourceModuleValue - input0) / (input1 - input0);

            // Now perform the cubic interpolation given the alpha value.
            return interp.CubicInterp(
              this.controlPoints[index0].outputValue,
              this.controlPoints[index1].outputValue,
              this.controlPoints[index2].outputValue,
              this.controlPoints[index3].outputValue,
              alpha);
        }

        /// Determines the array index in which to insert the control point
        /// into the internal control point array.
        ///
        /// @param inputValue The input value of the control point.
        ///
        /// @returns The array index in which to insert the control point.
        ///
        /// @pre No two control points have the same input value.
        ///
        /// @throw noise::ExceptionInvalidParam An invalid parameter was
        /// specified; see the preconditions for more information.
        ///
        /// By inserting the control point at the returned array index, this
        /// class ensures that the control point array is sorted by input
        /// value.  The code that maps a value onto the curve requires a
        /// sorted control point array.
        protected int FindInsertionPos(double inputValue)
        {
            int insertionPos;
            for (insertionPos = 0; insertionPos < this.controlPointCount; insertionPos++)
            {
                if (inputValue < this.controlPoints[insertionPos].inputValue)
                {
                    // We found the array index in which to insert the new control point.
                    // Exit now.
                    break;
                }
                else if (inputValue == this.controlPoints[insertionPos].inputValue)
                {
                    // Each control point is required to contain a unique input value, so
                    // throw an exception.
                    throw new Exception("invalid params");
                }
            }
            return insertionPos;
        }

        /// Inserts the control point at the specified position in the
        /// internal control point array.
        ///
        /// @param insertionPos The zero-based array position in which to
        /// insert the control point.
        /// @param inputValue The input value stored in the control point.
        /// @param outputValue The output value stored in the control point.
        ///
        /// To make room for this new control point, this method reallocates
        /// the control point array and shifts all control points occurring
        /// after the insertion position up by one.
        ///
        /// Because the curve mapping algorithm used by this noise module
        /// requires that all control points in the array must be sorted by
        /// input value, the new control point should be inserted at the
        /// position in which the order is still preserved.
        protected void InsertAtPos(int insertionPos, double inputValue, double outputValue)
        {
            ControlPoint cp = new ControlPoint();
            cp.inputValue = inputValue;
            cp.outputValue = outputValue;

            this.controlPoints.Insert(insertionPos, cp);

            this.controlPointCount++;
        }

        private int ClampValue(int value, int begin, int end)
        {
            if (value < begin)
            {
                value = begin;
            }
            else if (value >= end)
            {
                value = end - 1;
            }

            return value;
        }
    }
}

